package cn.iocoder.yudao.module.scrm.service.customizeproperty;

import cn.iocoder.yudao.framework.common.pojo.PageResult;
import cn.iocoder.yudao.framework.common.util.object.BeanUtils;
import cn.iocoder.yudao.module.scrm.controller.admin.customizeproperty.vo.CustomizePropertyPageReqVO;
import cn.iocoder.yudao.module.scrm.controller.admin.customizeproperty.vo.CustomizePropertySaveReqVO;
import cn.iocoder.yudao.module.scrm.dal.dataobject.customizeproperty.CustomizePropertyDO;
import cn.iocoder.yudao.module.scrm.dal.mysql.customizeproperty.CustomizePropertyMapper;
import org.springframework.stereotype.Service;
import org.springframework.validation.annotation.Validated;

import javax.annotation.Resource;
import java.util.List;

import static cn.iocoder.yudao.framework.common.exception.util.ServiceExceptionUtil.exception;
import static cn.iocoder.yudao.module.scrm.enums.ErrorCodeConstants.CUSTOMIZE_PROPERTY_NOT_EXISTS;

/**
 * 自定义字段 Service 实现类
 *
 * @author admin
 */
@Service
@Validated
public class CustomizePropertyServiceImpl implements CustomizePropertyService {

    @Resource
    private CustomizePropertyMapper customizePropertyMapper;

    @Override
    public Long createCustomizeProperty(CustomizePropertySaveReqVO createReqVO) {
        // 插入
        CustomizePropertyDO customizeProperty = BeanUtils.toBean(createReqVO, CustomizePropertyDO.class);
        customizePropertyMapper.insert(customizeProperty);
        // 返回
        return customizeProperty.getId();
    }

    @Override
    public void updateCustomizeProperty(CustomizePropertySaveReqVO updateReqVO) {
        // 校验存在
        validateCustomizePropertyExists(updateReqVO.getId());
        // 更新
        CustomizePropertyDO updateObj = BeanUtils.toBean(updateReqVO, CustomizePropertyDO.class);
        customizePropertyMapper.updateById(updateObj);
    }

    @Override
    public void deleteCustomizeProperty(Long id) {
        // 校验存在
        validateCustomizePropertyExists(id);
        // 删除
        customizePropertyMapper.deleteById(id);
    }

    private void validateCustomizePropertyExists(Long id) {
        if (customizePropertyMapper.selectById(id) == null) {
            throw exception(CUSTOMIZE_PROPERTY_NOT_EXISTS);
        }
    }

    @Override
    public List<CustomizePropertyDO> getCustomizeProperty(int type) {
        return customizePropertyMapper.selectList(CustomizePropertyDO::getType,type);
    }

    @Override
    public PageResult<CustomizePropertyDO> getCustomizePropertyPage(CustomizePropertyPageReqVO pageReqVO) {
        return customizePropertyMapper.selectPage(pageReqVO);
    }

}